<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="12" :xl="12" :lg="12" :md="24" :sm="24" :xs="24">
        <el-card style="margin-bottom: 20px">
          <template #header>
            <div class="card-header">
              <span>评论列表</span>
            </div>
          </template>

          <!-- 列表 -->
          <VTable
            :tableData="tableData"
            :options="options"
            @getSelection="handleSelection"
            @clickRow="handleClickRow"
          >
            <template #menubtn>
              <el-button type="primary" @click="handleAdd">新增</el-button>
              <el-button type="warning" @click="handleBatchDelete"
                >批量删除</el-button
              >
            </template>

            <template #operate="scope">
              <el-button
                size="small"
                link
                type="primary"
                :icon="View"
                @click="handleDetail(scope.row)"
                >查看</el-button
              >
              <el-button
                size="small"
                link
                type="primary"
                :icon="Edit"
                @click="handleEdit(scope.row)"
                >编辑</el-button
              >
              <el-button
                size="small"
                link
                type="danger"
                :icon="Delete"
                @click="handleDelete(scope.row.id)"
                >删除</el-button
              >
            </template>
          </VTable>
        </el-card>
      </el-col>

      <el-col :span="12" :xl="12" :lg="12" :md="24" :sm="24" :xs="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>回复列表</span>
            </div>
          </template>

          <VTable :options="sonOptions" :tableData="sonTableData">
            <template #menubtn>
              <el-button type="primary" @click="sonHandleAdd">新增</el-button>
            </template>
            <template #operate="scope">
              <el-button
                size="small"
                link
                type="primary"
                :icon="Edit"
                @click="sonHandleEdit(scope.row)"
                >编辑</el-button
              >
              <el-button
                size="small"
                link
                type="danger"
                :icon="Delete"
                @click="sonHandleDelete(scope.row.id)"
                >删除</el-button
              >
            </template>
          </VTable>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      style="width: 600px"
    >
      <!--新增/编辑  -->
      <el-form
        v-if="actionType === '新增' || actionType === '编辑'"
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
      >
        <el-form-item
          v-for="item in filterOptions"
          :key="item"
          :label="item.label"
          :prop="item.prop"
        >
          <el-autocomplete
            v-if="item.prop === 'title'"
            v-model="ruleForm[item.prop]"
            :fetch-suggestions="querySearchHomestay"
            clearable
            class="inline-input w-50"
            @select="handleSelectHomestay"
          />
          <el-autocomplete
            v-else-if="item.prop === 'username'"
            v-model="ruleForm[item.prop]"
            :fetch-suggestions="querySearchUsername"
            clearable
            class="inline-input w-50"
            @select="handleSelectUsername"
          />
          <el-input
            v-else-if="item.prop === 'content'"
            v-model="ruleForm[item.prop]"
            :rows="3"
            type="textarea"
          ></el-input>
          <el-rate
            v-else-if="item.type === 'rate'"
            v-model="ruleForm[item.prop]"
            :colors="colors"
          />
        </el-form-item>
      </el-form>

      <!-- 详情 -->
      <Description
        v-if="actionType === '查看'"
        :options="options"
        :dataItem="dataItem"
      ></Description>

      <template #footer>
        <el-button
          v-if="actionType === '新增' || actionType === '编辑'"
          @click="resetForm(ruleFormRef)"
          >关闭</el-button
        >
        <el-button v-if="actionType === '查看'" @click="dialogVisible = false"
          >关闭</el-button
        >
        <el-button
          v-if="actionType === '新增' || actionType === '编辑'"
          type="primary"
          @click="submitForm(ruleFormRef)"
        >
          确定
        </el-button>
      </template>
    </el-dialog>

    <el-dialog
      v-model="sonDialogVisible"
      :title="sonDialogTitle"
      style="width: 600px"
    >
      <!--新增/编辑  -->
      <el-form
        v-if="sonActionType === '新增' || sonActionType === '编辑'"
        ref="ruleFormRef"
        :model="sonRuleForm"
        :rules="sonRules"
        label-width="auto"
      >
        <el-form-item
          v-for="item in sonFilterOptions"
          :key="item"
          :label="item.label"
          :prop="item.prop"
        >
          <el-input
            v-if="item.prop === 'username'"
            disabled
            v-model="sonRuleForm[item.prop]"
          ></el-input>
          <el-input
            v-else
            v-model="sonRuleForm[item.prop]"
            :rows="3"
            type="textarea"
          ></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button
          v-if="sonActionType === '新增' || sonActionType === '编辑'"
          @click="resetForm(ruleFormRef)"
          >关闭</el-button
        >
        <el-button
          v-if="sonActionType === '查看'"
          @click="sonDialogVisible = false"
          >关闭</el-button
        >
        <el-button
          v-if="sonActionType === '新增' || sonActionType === '编辑'"
          type="primary"
          @click="submitForm(ruleFormRef)"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import {
  getAllComment,
  deleteComment,
  batchDeleteComment,
  addComment,
  updateComment,
  getReply,
  updateReply,
  getHostByCommentId,
  addReply,
  deleteReply,
} from "../../api/commentManage/index";
import VTable from "../../components/VTable/index.vue";
import Description from "../../components/Description/index.vue";
import { Delete, Edit, View, Plus, List } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getUserList,
  searchUser,
  getGuest,
  searchGuest,
} from "../../api/userManage/index";
import {
  getAllHomestay,
  searchHomestayByTitle,
  searchOnlineHomeByTitle,
  getAllOnlineHomeList,
} from "../../api/homestayManage/index";
import type {
  FormInstance,
  FormRules,
  UploadProps,
  UploadFile,
} from "element-plus";
const colors = ref(["#99A9BF", "#F7BA2A", "#FF9900"]);
const tableData = ref<any>([]);
const options = [
  {
    prop: "username",
    label: "评论人",
    isTable: true,
    isForm: true,
  },
  {
    prop: "content",
    label: "内容",
    isTable: true,
    width: 200,
    isForm: true,
  },
  {
    prop: "createTime",
    label: "评论时间",
    isTable: true,
    width: 200,
    type: "time",
  },
  {
    prop: "totalScore",
    label: "总评分",
    isTable: true,
  },
  {
    prop: "deviceScore",
    label: "设施评分",
    isTable: true,
    isForm: true,
    type: "rate",
  },
  {
    prop: "serviceScore",
    label: "服务评分",
    isTable: true,
    isForm: true,
    type: "rate",
  },
  {
    prop: "healthScore",
    label: "卫生评分",
    isTable: true,
    isForm: true,
    type: "rate",
  },
  {
    prop: "title",
    label: "房源",
    isTable: false,
    isForm: true,
  },
];

const sonTableData = ref<any>([]);
const sonOptions = [
  {
    prop: "username",
    label: "房东",
    isTable: true,
    isForm: true,
  },
  {
    prop: "content",
    label: "内容",
    isTable: true,
    width: 200,
    isForm: true,
  },
  {
    prop: "createTime",
    label: "回复时间",
    isTable: true,
    width: 200,
    type: "time",
  },
];

const filterOptions = options.filter((item) => item.isForm == true);
const sonFilterOptions = sonOptions.filter((item) => item.isForm == true);

const dialogTitle = ref("查看"); // 弹出层标题
const dialogVisible = ref<boolean>(false);
const actionType = ref(""); // 操作按钮的类型
const setDialogTile = (type: string) => {
  dialogTitle.value = type;
  actionType.value = type;
  dialogVisible.value = true;
};

//新增/编辑
const ruleFormRef = ref<FormInstance>();
//新增
const handleAdd = () => {
  ruleForm = reactive({
    userId: "",
    houseId: "",
    content: "",
    deviceScore: Number,
    serviceScore: Number,
    healthScore: Number,
  });
  setDialogTile("新增");
};
//自动补全
const querySearchUsername = async (name, callback) => {
  const list = [];
  if (name) {
    const res = await searchGuest({ username: name });
    res.data.data.forEach((item) => {
      list.push({ value: item.username, id: item.id });
    });
  } else {
    const res = await getGuest();
    res.data.data.forEach((item) => {
      list.push({ value: item.username, id: item.id });
    });
  }
  callback(list);
};
const querySearchHomestay = async (name, callback) => {
  const list = [];
  if (name) {
    const res = await searchOnlineHomeByTitle({ title: name });
    res.data.data.forEach((item) => {
      list.push({ value: item.title, id: item.id });
    });
  } else {
    const res = await getAllOnlineHomeList();
    res.data.data.forEach((item) => {
      list.push({ value: item.title, id: item.id });
    });
  }
  callback(list);
};
//选中
const handleSelectUsername = (item, $event) => {
  ruleForm.userId = item.id;
};
const handleSelectHomestay = (item, $event) => {
  ruleForm.houseId = item.id;
};

let ruleForm = reactive({
  userId: "",
  houseId: "",
  content: "",
  deviceScore: Number,
  serviceScore: Number,
  healthScore: Number,
});

//编辑
const handleEdit = async (scope: any) => {
  ruleForm = scope;
  console.log(ruleForm);
  setDialogTile("编辑");
};

//子组件新增编辑
const sonDialogTitle = ref("查看"); // 弹出层标题
const sonDialogVisible = ref<boolean>(false);
const sonActionType = ref(""); // 操作按钮的类型
const setSonDialogTile = (type: string) => {
  sonDialogTitle.value = type;
  sonActionType.value = type;
  sonDialogVisible.value = true;
};

let sonRuleForm = reactive({
  commentId: Number,
  id: Number, //回复id
  userId: Number,
  username: "",
  content: "",
});
const sonHandleEdit = async (scope: any) => {
  sonRuleForm = scope;
  setSonDialogTile("编辑");
};
const sonHandleAdd = () => {
  sonRuleForm = reactive({
    commentId: clickId.value,
    id: Number, //回复id
    userId: hostId.value,
    username: username.value,
    content: "",
  });
  setSonDialogTile("新增");
};
//删除
const sonHandleDelete = (id: number) => {
  ElMessageBox.confirm("确认删除此项数据?", "系统提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await deleteReply(id);
      if (res.data.success == true) {
        ElMessage({
          message: res.data.msg,
          type: "success",
        });
      } else {
        ElMessage.error(res.data.msg);
      }
      await getNewReply(clickId.value);
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

//关闭
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  if (actionType.value === "新增") {
    formEl.resetFields();
  }
  dialogVisible.value = false;
  sonDialogVisible.value = false;
};

//详情
const dataItem = ref<object>({});
const handleDetail = (scope: any) => {
  dataItem.value = scope;
  setDialogTile("查看");
  console.log(dataItem);
};

//删除
const handleDelete = (id: number) => {
  ElMessageBox.confirm("确认删除此项数据?", "系统提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await deleteComment(id);
      if (res.data.success == true) {
        ElMessage({
          message: res.data.msg,
          type: "success",
        });
      } else {
        ElMessage.error(res.data.msg);
      }
      await onLoad();
      sonTableData.value = [];
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

//子组件传值--点击行
const clickId = ref<number>();
const username = ref<string>("");
const hostId = ref<number>();
const handleClickRow = async (val: any) => {
  clickId.value = val.id;
  const res = await getReply(val.id);
  sonTableData.value = res.data.data;
  console.log("子组件表格：", sonTableData.value);

  const r = await getHostByCommentId(val.id);
  username.value = r.data.data[0].username;
  hostId.value = r.data.data[0].hostId;
};

//子组件传值--多选
const ids = ref<any>([]);
const handleSelection = (val: any) => {
  console.log("子组件传值：", val);
  const selecction: any = [];
  val.forEach((item: any) => {
    selecction.push(item.id);
  });
  ids.value = selecction;
};
// 批量删除
const handleBatchDelete = async () => {
  if (ids.value.length == 0) {
    ElMessage({
      type: "info",
      message: "请选择数据",
    });
    return;
  }
  ElMessageBox.confirm("确认删除这些数据?", "系统提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await batchDeleteComment(ids.value);
      if (res.data.success) {
        ElMessage({
          message: res.data.msg,
          type: "success",
        });
      } else {
        ElMessage.error(res.data.msg);
      }
      await onLoad();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

const getNewReply = async (val) => {
  clickId.value = val;
  const res = await getReply(val);
  sonTableData.value = res.data.data;
};

// 提交
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  console.log(sonRuleForm);

  if (actionType.value === "新增") {
    const res = await addComment(ruleForm);
    if (res.data.success == true) {
      ElMessage({
        message: res.data.msg,
        type: "success",
      });
      onLoad();
    } else {
      ElMessage.error(res.data.msg);
    }
  } else if (actionType.value === "编辑") {
    const res = await updateComment(ruleForm);
    if (res.data.success) {
      if (res.data.success == true) {
        ElMessage({
          message: res.data.msg,
          type: "success",
        });
        onLoad();
      } else {
        ElMessage.error(res.data.msg);
      }
    }
  } else if (sonActionType.value == "编辑") {
    const res = await updateReply(sonRuleForm);
    if (res.data.success) {
      if (res.data.success == true) {
        ElMessage({
          message: res.data.msg,
          type: "success",
        });
        await getNewReply(clickId.value);
      } else {
        ElMessage.error(res.data.msg);
      }
    }
  } else if (sonActionType.value == "新增") {
    const res = await addReply(sonRuleForm);
    if (res.data.success) {
      if (res.data.success == true) {
        ElMessage({
          message: res.data.msg,
          type: "success",
        });
        await getNewReply(clickId.value);
      } else {
        ElMessage.error(res.data.msg);
      }
    }
  }
  dialogVisible.value = false;
  sonDialogVisible.value = false;
};

const onLoad = async () => {
  const res = await getAllComment();
  tableData.value = res.data.data;
};

onMounted(async () => {
  await onLoad();
});
</script>
